﻿/*
 * KLF Headless Browser
 * Written by Kris Oye <kristianoye@gmail.com>
 * Copyright (C) 2011-2012.  All rights reserved.
 */
namespace KLF.Lib.Browser.DOM.CSS.SAC.Selectors
{
    #region Using Statements

    using System;
    using KLF.Lib.Browser.DOM.HTML;

    #endregion

    public class DescendantSelector : BinarySelector
    {
        public DescendantSelector(Selector l, Selector r)
            : base(l, r)
        {
        }

        public override bool Matches(HTMLElement e)
        {
            if (Right == null || Left == null)
                throw new Exception("Attempted to evaluate poorly formated AdjacentSelector.");

            //  Left Right
            if (Right.Matches(e) && e.Parent != null)
            {
                HTMLElement p = e.Parent as HTMLElement;

                do
                {
                    if (Left.Matches(p))
                        return true;

                    p = p.Parent as HTMLElement;
                }
                while (p != null);
            }
            return false;
        }

        public override SelectorType Type
        {
            get
            {
                return SelectorType.ElementNodeSelector;
            }
        }

        public override string ToString()
        {
            return String.Format("{0} {1}", Left, Right);
        }
    }
}
